package com.yanyeori.framework.log.common.filter;

import com.yanyeori.framework.log.common.util.LogUtil;
import com.yanyeori.framework.log.common.wrapper.BufferedRequestWrapper;
import com.yanyeori.framework.log.common.wrapper.BufferedResponseWrapper;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Log过滤器
 *
 * @author chenkuan 2022/11/18
 */
@WebFilter(urlPatterns = "/*")
public class LogFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ServletRequest requestWrapper = buildRequestWrapper(request);
        ServletResponse responseWrapper = buildResponseWrapper(response);

        chain.doFilter(requestWrapper, responseWrapper);

        removeWrapper(requestWrapper, responseWrapper);
    }

    private ServletRequest buildRequestWrapper(ServletRequest request) throws IOException {
        return request instanceof HttpServletRequest && LogUtil.isRepeatReadStream(request) ? new BufferedRequestWrapper((HttpServletRequest) request) : request;
    }

    private ServletResponse buildResponseWrapper(ServletResponse response) {
        return response instanceof HttpServletResponse ? new BufferedResponseWrapper((HttpServletResponse) response) : response;
    }

    private void removeWrapper(ServletRequest request, ServletResponse response) {
        if (request instanceof BufferedRequestWrapper) {
            ((BufferedRequestWrapper) request).clear();
        }
    }
}
